<?php
namespace App\Repositories\BLL;
use App\Repositories\BLL\Repository;
use App\Models\Wechat\WechatUser;
use Illuminate\Support\Facades\DB;

class WechatUserBLL extends Repository
{		
	public function model()
	{
		return WechatUser::class;
	}
	
	public function ajaxIndex($currentRouteName)
	{
		// datatables请求次数
	    	$draw = request('draw', 1);
	    	// 开始条数
		$start = request('start',config('admin.global.list.start'));
		// 每页显示数目
		$length = request('length',config('admin.global.list.length'));
		// 排序
	    $order['name'] = request('columns.' .request('order.0.column',0) . '.name');
	    $order['dir'] = request('order.0.dir','asc');

	    $search['value'] = request('search.value','');

	    $search['regex'] = request('search.regex',false);

	    $wall = $this->model;

	    // 搜索框中的值
	    if ($search['value']) {
	        if($search['regex'] == 'true'){
	            $wall = $wall->where('nickname', 'like', "%{$search['value']}%");
	        }else{
	            $wall = $wall->where('nickname', $search['value']);
	        }
	    }

	    $count = $wall->count();

	    $wall = $wall->orderBy($order['name'], $order['dir']);
    		$walls = $wall->offset($start)->limit($length)->get();
			
		$pointPost = strrpos($currentRouteName,'.');
		$parentUrl = substr($currentRouteName,0,$pointPost);
		
	    	//datatables固定返回格式
	    	return [
	        'draw' => $draw,
	        'recordsTotal' => $count,
	        'recordsFiltered' => $count,
	        'data' => $walls,
	    ];
	}

	public function createEntity($attributes)
	{
		$result = $this->create($attributes);
		if ($result) {
			return TRUE;
		}else{
			return FALSE;
		}
	}
	
	public function editView($id)
	{
		$user = $this->find($id);
		if ($user) {
			return $user;
		}
		abort(404);
	}

	public function updateEntity($attributes,$id)
	{
		$result = $this->update($attributes,$id);
		if ($result) {
			return TRUE;
		}else{
			return FALSE;
		}
	}
	
	public function updateUser($user){
		//查询用户是否存在
		$dbUser = $this->findByField('openid',$user['openid'])->first();
		if($dbUser){
			//更新
			if(!$this->updateEntity($user, $dbUser['id'])){
				return FALSE;
			}
		}else{
			//新增
			if(!$this->createEntity($user)){
				return FALSE;
			}
		}
		return TRUE;
	}
	
	public function updateAllUsers($users){
		foreach($users as $user){
			$result = $this->updateUser($user);
			if(!$result){
				return FALSE;
			}
		}
		return TRUE;
	}
	
}
